<template>
  <el-dialog v-model="open" :title="t('finaPaymentSetting')" width="420px">
    <div>
      <el-form
        :model="editFrom"
        ref="editFromRef"
        :rules="formRules"
        label-width="80px"
        label-position="right"
      >
        <el-form-item :label="t('price')" prop="final_money">
          <el-input v-model.trim="editFrom.final_money" maxlength="30" />
        </el-form-item>
        <el-form-item :label="t('finalMoneyRemark')" prop="final_money_remark">
          <el-input v-model.trim="editFrom.final_money_remark" type="textarea" rows="4" maxlength="200" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="open = false">{{ t("cancel") }}</el-button>
        <el-button type="primary" :loading="loading" @click="submitForm(editFromRef)">
          {{ t("confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { t } from "@/lang";
import { FormInstance } from "element-plus";
import { orderFinalMoney } from "@/addon/shop/api/order";

const open = ref(false);
const loading = ref(false);
const editFromRef = ref<FormInstance>();
const editFrom = ref<any>({
  order_id: "",
  final_money: "",
  final_money_remark: "",
});
const emit = defineEmits(["complete"]);

// 表单验证规则
const formRules = computed(() => {
  return {
    final_money: [{ required: true, message: t("pricePlaceholder"), trigger: "blur" }],
  };
});

const setFormData = (row: any = {}) => {
  if (row) {
    editFrom.value.order_id = row.order_id;
    editFrom.value.final_money = row.final_money;
    editFrom.value.final_money_remark = row.final_money_remark;
    open.value = true;
  }
};

// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (loading.value || !formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      orderFinalMoney(editFrom.value)
        .then((res) => {
          emit("complete");
          open.value = false;
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

defineExpose({
  open,
  setFormData,
});
</script>
